﻿using System;
using System.Collections.Generic;
using System.Text;

using Csla;
using Csla.Data;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace buildingLib
{
    [Serializable()]
    public class Members:BusinessListBase<Members,Member>
    {
        #region Business Methods
        #endregion

        #region Factory Methods
        public static Members NewMembers()
        {
            return new Members();
        }

        public static Members GetMembers(Guid ownerid)
        {
            return new Members(ownerid);
        }

        private Members()
        {
            MarkAsChild();
        }

        private Members(Guid ownerid)
        {
            MarkAsChild();
            Fetch(ownerid);
        }
        #endregion

        #region DataAccess
        private void Fetch(Guid ownerid)
        {
            this.RaiseListChangedEvents = false;
            Database db = SQLDatabase.GetDatabase();
            DbCommand dbcom = db.GetStoredProcCommand("usp_GGetOwnerMembers");
            db.AddInParameter(dbcom, "id", DbType.Guid, ownerid);
            using (SafeDataReader dr = new SafeDataReader(db.ExecuteReader(dbcom)))
            {
                while (dr.Read())
                    this.Add(Member.GetMember(dr));
            }

            this.RaiseListChangedEvents = true;
        }

        internal void Update()
        {
            this.RaiseListChangedEvents = false;
            // update (thus deleting) any deleted child objects
            foreach (Member obj in DeletedList)
                obj.DeleteSelf();
            // now that they are deleted, remove them from memory too
            DeletedList.Clear();

            // add/update any current child objects
            foreach (Member obj in this)
            {
                if (obj.IsNew)
                    obj.Insert();
                else
                    obj.Update();
            }
            this.RaiseListChangedEvents = true;
        }
        #endregion
    }
}
